#!/bin/bash
#
# Copyright 2015-2017 Adrian DC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# === Repo Out Cleaner ===
function repoclean()
{
  # Usage: repoclean (Delete contents from 'out' folder)

  # Delete contents from 'out' folder
  echo '';
  echo ' repoclean: Cleaning out folder...';
  find out/ -mindepth 1 -delete;
  echo '';
}

# === Repo Out Device Cleaner ===
function repodevclean()
{
  # Usage: repodevclean (Delete contents from 'out/target/product' folder)

  # Delete contents from 'out/target/product' folder
  echo '';
  echo ' repodevclean: Cleaning out/target/product folder...';
  find out/target/product/ -mindepth 1 -delete;
  echo '';
}

# === Repo Projects Cleaner ===
function repoprojectscleaner()
{
  # Usage
  if [ ! -d '.repo' ]; then
    echo '';
    echo ' Usage: repoprojectscleaner (Run inside an Android repo root)';
    echo '';
    return;
  fi;

  # Variables
  local git_folders;
  local git_projects;
  local git_project_objects;

  # Search
  echo '';
  echo ' Starting the git folders detection...';
  echo '';
  # shellcheck disable=SC2016
  git_folders=$(repo forall -c 'echo -n "$(dirname $(readlink -f .git/info)) ${REPO_PATH} ";');

  # Analyse
  echo '';
  echo ' Studying the .repo /project-objects folder...';
  echo '';
  git_projects=$(find .repo/project-objects -name '*.git');
  for git_path in ${git_projects}; do
    if [[ ! "${git_folders}" == *"${git_path}"* ]]; then
      echo -n "  Objects ${git_path} are unreferenced. Delete [y/N] ? ";
      read -r key;
      if [[ "${key}" == 'y' || "${key}" == 'Y' ]]; then
        rm -rf "${git_path}";
      fi;
    fi;
  done;
  echo '';

  # Cleanup
  echo '';
  echo ' Studying the .repo/projects folder...';
  echo '';
  git_project_objects=$(find .repo/project-objects -name '*.git');
  cd .repo/projects/;
  git_projects=$(find . -name '*.git' | cut -c 3-);
  for git_path in ${git_project_objects}; do
    if [[ ! "${git_project_objects}" == *"${git_path}"* ]]; then
      echo "  Project ${git_path} is unreferenced. Deleting [y/N] ? ";
      read -r key;
      if [[ "${key}" == 'y' || "${key}" == 'Y' ]]; then
        rm -rf "${git_path}";
      fi;
    fi;
  done;
  cd ../../;
  echo '';
}

# === Repo Tags Cleaner ===
function repotagscleaner()
{
  # Usage
  if [ ! -d '.repo' ]; then
    echo '';
    echo ' Usage: repotagscleaner (Run inside an Android repo root)';
    echo '';
    return;
  fi;

  # Search
  echo '';
  echo ' Starting the projects analysis...';
  echo '';
  # shellcheck disable=SC2016
  repo forall -c 'tags_output=$(git tag 2>&1
                              | grep -v "${REPO_RREV##*/}$");
                  if [ ! -z "${tags_output}" ]; then
                    echo "";
                    echo " Project: ${REPO_PROJECT} [${REPO_REMOTE}/${REPO_RREV##*/}]";
                    echo "";
                    git tag
                        | grep -v ${REPO_RREV##*/}
                        | xargs git tag -d 2> /dev/null;
                    tags_output=$(git tag 2>&1
                              | grep -v "${REPO_RREV##*/}$");
                    if [ ! -z "${tags_output}" ]; then
                      git fetch --all --prune --tags;
                      git tag
                          | grep -v ${REPO_RREV##*/}
                          | xargs git tag -d 2> /dev/null;
                    fi;
                    git fetch --prune ${REPO_REMOTE} ${REPO_RREV##*/};
                  fi;';
}

# === Repo Heads Cleaner ===
function repoheadscleaner()
{
  # Usage
  if [ -z "${1}" ]; then
    echo '';
    echo ' Usage: repoheadscleaner (Cleanup repo projects refs/ contents)';
    echo '';
    return;
  fi;

  # Cleanup repo projects refs/ contents
  echo '';
  # shellcheck disable=SC2016
  repo forall -c 'echo " Project ${REPO_PROJECT} : ${REPO_REMOTE}/${REPO_RREV##*/}";
                  git show-ref 2>&1 > /dev/null |
                    while read -r line; do
                     refs_path=$(echo ${line} | sed "s/.*\(refs.*\) does.*/\1/");
                     echo "  Deleting ${refs_path}...";
                     rm .git/${refs_path} .git/logs/${refs_path};
                   done;';
  echo '';
}

# === Repo Forced Sync Project ===
function reposyrm()
{
  # Usage
  if [ -z "${1}" ]; then
    echo '';
    echo ' Usage: reposyrm <project/relative/path> (Project repo sync with removal)';
    echo '';
    return;
  fi;

  # Perform actions
  local project_path;
  for project_paths in "${@}"; do
    project_path=${project_paths%/};
    rm -rfv "${project_path}";
    rm -rfv ".repo/projects/${project_path}.git";
    reposy "${project_path}";
    echo '';
  done;
}

# === Repo Forced Sync Project ===
function reposyrmf()
{
  # Usage
  if [ -z "${1}" ]; then
    echo '';
    echo ' Usage: reposyrmf <project/relative/path> (Project repo sync with forced removal)';
    echo '';
    return;
  fi;

  # Perform actions
  local project_path;
  for project_paths in "${@}"; do
    project_path=${project_paths%/};
    sudo rm -rfv "${project_path}";
    sudo rm -rfv ".repo/projects/${project_path}.git";
    sudo rm -rfv ".repo/project-objects/${project_path}.git";
    reposy "${project_path}";
    echo '';
  done;
}

# === Repo CCache Cleaner ===
alias repocleancache='if [ ! -z "${CCACHE_DIR}" ]; then rm -rfv "${CCACHE_DIR}/"*; fi';
